﻿using Sustainalytics.LongRunningTaskManager.Interface;
using System.Collections.Generic;
using System.Configuration;

namespace Sustainalytics.LongRunningTaskManager
{
    /// <summary>
    /// Task manager settings.
    /// </summary>
    public class LongRunningTaskManagerSettings : ConfigurationSection, ILongRunningTaskManagerSettings, IEqualityComparer<LongRunningTaskManagerSettings>
    {
        private static class ConfigurationPropertyNames
        {
            public const string MaxOverallManagedTasks = "maxOverallManagedTasks";
            public const string MaxTasksPerUser = "maxTasksPerUser";
        }

        /// <summary>
        /// Maximum number of managed tasks that will be allocated to run Long Running Tasks.
        /// </summary>
        [ConfigurationProperty(ConfigurationPropertyNames.MaxOverallManagedTasks)]
        public int MaxOverallManagedTasks
        {
            get { return (int?)this[ConfigurationPropertyNames.MaxOverallManagedTasks] ?? 30; }
            set { this[ConfigurationPropertyNames.MaxOverallManagedTasks] = value; }
        }

        /// <summary>
        /// Maximum number of tasks that may be allocated per user.
        /// </summary>
        [ConfigurationProperty(ConfigurationPropertyNames.MaxTasksPerUser)]
        public int MaxTasksPerUser
        {
            get { return (int?)this[ConfigurationPropertyNames.MaxTasksPerUser] ?? 5; }
            set { this[ConfigurationPropertyNames.MaxTasksPerUser] = value; }
        }


        /// <summary>
        /// Create settings based on configuration.
        /// </summary>
        /// <returns> Task manager settings. </returns>
        public static LongRunningTaskManagerSettings FromConfig()
        {
            string configSectionName = "longRunningTaskManager";

            LongRunningTaskManagerSettings settings = (LongRunningTaskManagerSettings)ConfigurationManager.GetSection(configSectionName);

            if (settings == null)
            {
                throw new LongRunningTaskManagerSettingsNotFoundException(configSectionName);
            }

            return settings;
        }


        public bool Equals(LongRunningTaskManagerSettings x, LongRunningTaskManagerSettings y)
        {
            if (x == null && y == null)
                return true;

            if (x == null || y == null)
                return false;

            return (x.MaxOverallManagedTasks == y.MaxOverallManagedTasks)
                && (x.MaxTasksPerUser == y.MaxTasksPerUser);
        }

        public int GetHashCode(LongRunningTaskManagerSettings obj)
        {
            return this.MaxOverallManagedTasks.GetHashCode() | this.MaxTasksPerUser.GetHashCode();
        }
    }
}
